﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;

namespace Zero.UControl.Component
{
    public partial class Badge : ContentControl
    {
        private bool _isTemplateApplied;

        static Badge()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Badge),
                new FrameworkPropertyMetadata(typeof(Badge)));
        }

        public string BadgeTitle
        {
            get { return (string)GetValue(BadgeTitleProperty); }
            set { SetValue(BadgeTitleProperty, value); }
        }

        public static readonly DependencyProperty BadgeTitleProperty =
            DependencyProperty.Register("BadgeTitle", typeof(string), typeof(Badge), new PropertyMetadata("", OnValueChanged));


        public static readonly RoutedEvent TitleChangedEvent =
            EventManager.RegisterRoutedEvent("TitleChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Badge));

        public event RoutedEventHandler TitleChanged
        {
            add => AddHandler(TitleChangedEvent, value);
            remove => RemoveHandler(TitleChangedEvent, value);
        }


        public BadgeType TypeMode
        {
            get { return (BadgeType)GetValue(TypeModeProperty); }
            set { SetValue(TypeModeProperty, value); }
        }

        public static readonly DependencyProperty TypeModeProperty =
            DependencyProperty.Register("TypeMode", typeof(BadgeType), typeof(Badge), new PropertyMetadata(BadgeType.Title));


        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var badge = d as Badge;
            if (badge == null) return;
            if (!badge._isTemplateApplied) return;

            badge.RaiseEvent(new RoutedEventArgs(TitleChangedEvent, badge));
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _isTemplateApplied = true;
            var border = GetTemplateChild("border") as Border;
            var innerBorder = GetTemplateChild("innerBorder") as Border;

            this.Loaded += (s, e) =>
            {
                double x = this.ActualWidth - border.ActualWidth / 2;
                double y = -(border.ActualHeight / 5 * 3);
                if (border != null)
                {
                    Canvas.SetLeft(border, x);
                    Canvas.SetTop(border, y);
                }
                if (innerBorder != null)
                {
                    Canvas.SetLeft(innerBorder, x);
                    Canvas.SetTop(innerBorder, y);
                }
            };
        }
    }

    public enum BadgeType
    {
        Title,
        Ripple
    }
}
